#!/usr/bin/env php
<?php
// -----------------------------------------------------------------------------
// sdefastsearch - A PHP Fast ESP Search API
// Copyright (C) 2008,2009 sueddeutsche.de GmbH, Hultschiner Str. 8, D-81677 München
// www.sueddeutsche.de.de - Andreas.Scheerer@sueddeutsche.de
//
// This file is part of sdefastsearch.
//
// sdefastsearch is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------------

/**
 * Cli example showing spell check (did you mean) usage.
 * 
 * @author  Andreas Scheerer <Andreas.Scheerer@sueddeutsche.de
 * @version $Id: spellcheckSearch.php 20 2010-01-28 14:33:07Z kenn.north $ 
 */

//--------------------------------------------------------------------------
//---                               config                               ---
//-------------------------------------------------------------------------- 
set_include_path(dirname(__FILE__).'/../../src/');

//--------------------------------------------------------------------------
//---                               includes                             ---
//-------------------------------------------------------------------------- 
require_once 'sde/fastsearch/SearchFactory.php';
require_once 'sde/fastsearch/query/Query.php';
require_once 'sde/fastsearch/result/QueryTransformationName.php';

//--------------------------------------------------------------------------
//---                                 main                               ---
//-------------------------------------------------------------------------- 

// Params
// remove script name
array_shift($argv);
if (count($argv) < 2) {
    showInfo();
    exit();
}

$host         = $argv[0];
$port         = $argv[1];
$query        = "";
$querySuggest = "";
$viewName     = "";
$suggestStr   = "";

if (count($argv) > 2)
   $viewName = $argv[2];

// Properties
$properties = array (
    'fastsearch.SearchFactory' => "http.HttpSearchFactory",
    'fastsearch.http.qservers' => "$host:$port"
    );

try {
    // Get search factory
    $searchFactory = SearchFactory::newInstance($properties);

    // Printing list of views.
    if (empty($viewName)) {
        $list = $searchFactory->getSearchViewList();
    
        print "Views located at $host:$port\n";
    
        if (count($list) > 0) {
            for ($i = 0; $i < count($list); $i++) 
                print $list[$i]."\n";
        } else {
            print "No views found.\n";
        }
        exit();
    }

    // Get view.
    $view = $searchFactory->getSearchView($viewName);
    
    // Create the query and do a search.              
    for ($i = 3; $i < count($argv); $i++) {
        if (substr(trim($argv[$i]),0,1) == '-' ) continue; 
        $query .= $argv[$i];
        $query .= " ";
    }
    
    $query = str_replace('"', '\"', $query);
    $query = 'string("'.trim($query).'", mode=simpleall)';
    
    $theQuery = new Query();
    $theQuery->setQueryString($query);
    $theQuery->setParameterByType(BaseParameter::SPELL, 'suggest');

    $result = $view->search($theQuery);
    
    // spell checking
    $spellTransformations = $result->getQueryTransformations()
        ->getSuggestionsByName(QueryTransformationName::DID_YOU_MEAN);

    $transIter = $spellTransformations->getIterator();
    while($transIter->valid()) {
        if ($transIter->current()->getMessageID() == 2) {
            $querySuggest = $transIter->current()->getQuery(); 
        } elseif ($transIter->current()->getMessageID() == 7) {
            $suggestStr .= $transIter->current()->getCustom()." ";    
        }
        $transIter->next();
    }
    
    if (empty($querySuggest)) {
        print "There are no spell suggestions in the search result\n"; 
        exit();
    }
    
    echo $result->getHttpSearchURL();
    
    // Print out spell suggestion
    print "FIRST SEARCH RESULT\n===================\n";
    print "(".$result->getDocCount()." documents)\n";
    print "Query string: " . $theQuery->getQueryString() . "\n";
    print "Query suggestion: ".$suggestStr."\n\n";
    
    $spellQuery = new Query();
    $spellQuery->setQueryString($querySuggest); 

    $spellResult = $view->search($spellQuery); 
    
    // Dump the new drill downed search result to the terminal window
    print "\nSEARCH RESULT AFTER SPELL CORRECTION\n====================================\n";
    print "(".$spellResult->getDocCount()." documents)\n";
    print "Query string: " . $spellQuery->getQueryString() . "\n\n";
    
    $documentIterator = $spellResult->documents();
    
    while ($documentIterator->valid()) {
        $documentSummary = $documentIterator->current();
        print "-------- DocNo #".$documentSummary->getDocNo()." --------\n";
        print "[collection] "
            .$documentSummary->getSummaryFieldByName('collection')->getStringValue()."\n";
        print "[title] "
            .$documentSummary->getSummaryFieldByName('title')->getStringValue()."\n";
        print "[body] "
            .$documentSummary->getSummaryFieldByName('body')->getStringValue()."\n\n";
        $documentIterator->next();
    }
    
    // Exit
    print "Execution complete.\n";

} catch (ConfigurationException $e) {
    print "CONFIG_ERROR: ".$e->getMessage()."\n\nException trace:\n";
    print $e->getTraceAsString();
    exit(1);
} catch (Exception $e) {
    print "ERROR: ".$e->getMessage()."\n\nException trace:\n";
    print $e->getTraceAsString();
    exit(1);
}


//--------------------------------------------------------------------------
//---                             functions                              ---
//-------------------------------------------------------------------------- 
function showInfo() {
    print "usage: spellcheckSearch.php <host> <port> [view] [one or more query terms]\n";
    print "If no view and query term(s) are given, a list of avaible views will be shown.\n";
    print "example: spellcheckSearch.php localhost 15100 myview George Washington\n";
}
